package com.wk.unittestshow.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * //使用
 * recyclerViewSwipe.addItemDecoration(new MarginDecoration(getActivity()));
 */
public class RecyclerViewMarginDecoration extends RecyclerView.ItemDecoration {
    private int margin;
    private Paint mPaint ;

    public RecyclerViewMarginDecoration(Context context) {
        margin = 10 ; //间隔 px ,修改成自己需要的
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.GRAY);
    }

    /**
     * 针对RecyclerView本身 。
     * 可以在此进行更加精细的控制，比如每行的间隔颜色显示不一样。
     * 颜色绘制的原理就是： 将每个item 之间的间隙绘制上颜色即可。
     */
    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);

        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = parent.getChildAt(i);
            int index = parent.getChildAdapterPosition(view);

            if (index == 0) {
                continue;
            }

            int color= i%2==0 ? Color.parseColor("#06cebc") :Color.parseColor("#3b99ff") ;
            mPaint.setColor( color);

            float dividerTop = view.getTop() - margin;
            float dividerLeft = parent.getPaddingLeft() + margin;
            float dividerBottom = view.getTop();
            float dividerRight = parent.getWidth() - parent.getPaddingRight() - margin;
            c.drawRect(dividerLeft, dividerTop, dividerRight, dividerBottom, mPaint);
        }
    }

    /**
     * 针对 每一个 item
     */
    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view,
                               @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (parent.getChildAdapterPosition(view) != 0) {
            outRect.top =   margin;  // 间隔 ，outRect.top / bottom /left  /right
        }
    }
}
